<template>
	<u-index-list :scrollTop="scrollTop" @select="selectT">
		<view v-for="(item, index) in indexList" :key="index">
			<u-index-anchor :index="item" />
			<view v-if="item == it.first" class="list-cell" v-for="(it, i) in city" :key="i" @click="chooseCity(it)">
				<text >{{ it.name }}</text>
			</view>
		</view>
	</u-index-list>
</template>

<script>
	export default {
		data() {
			return {
				scrollTop: 0,
				indexList: [],
				city:[]
			}
		},
		onPageScroll(e) {
			this.scrollTop = e.scrollTop;
		},
		onShow() {
			this.getTreeCity()
		},
		methods: {
		
			getTreeCity() {
				this.$axios.request(this.$api.getTreeCity, "GET").then((val) => {
					val.data.forEach((item,index) => {
						if(this.indexList.includes(item.first) == false){
							this.indexList.push(item.first)
						}
					})
					
					this.city = val.data
				})
				
			},
			selectT(e) {
				console.log("e: ", e);
			},
			chooseCity(city) {
				const pages = getCurrentPages() //获取所有页面放到pages里面
				const page = pages[pages.length - 2] //获取到上一个页面
				uni.setStorageSync("city",city)
				this.$store.commit("setCity",city)
				
				var token = uni.getStorageSync("token")
				var userinfo = uni.getStorageSync("userinfo")
				if(token && userinfo){
					
					this.$wechat.getcode().then((code) => {
						this.$axios.request(this.$api.getOpenId,"GET",{
							code:code.code
						}).then((openData)=>{
							this.$axios.request(this.$api.login,"POST",{
								openId:userinfo.openId,
								nickname:userinfo.nickName,
								avatar:userinfo.avatarUrl,
								tenantCode:city.tenantCode
							}).then((loginData) => {
								
								uni.setStorageSync("token",loginData.data.token)
								uni.setStorageSync("userinfo",loginData.data.user)
								this.$store.commit("setUserinfo",loginData.data.user)
							
							})
						})
					})
				}
				uni.navigateBack() //返回到上一页
			}
		}
	}
</script>

<style lang="scss" scoped>
	.list-cell {
		display: flex;
		box-sizing: border-box;
		width: 100%;
		padding: 10px 24rpx;
		overflow: hidden;
		color: #323233;
		font-size: 14px;
		line-height: 24px;
		background-color: #fff;
	}
</style>
